<template lang="pug">
  .page
    .AccountsReceivableManage
      .search-form.mb-10.pl-10.pr-10
        Form.ivu-row.ivu-form-basic(ref="formData" :model="formData" :rules="rules" :label-width="90" v-if='hasFind')
          FormItem.form-item.ivu-col.pr-20.mb-15(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
            template(v-if="item.type === 'select'")
              Select(v-if="item.fn" v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable :disabled="item.isDisabled" @on-change="listenCall(item.fn, item.model, $event)")
                Option(
                  v-for="(c_item, index) in arrListDown[item.options]"
                  :value="c_item.value"
                  :key="index"
                ) {{ c_item.label }}
              Select(v-else v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable :disabled="item.isDisabled")
                Option(
                  v-for="(c_item, index) in arrListDown[item.options]"
                  :value="c_item.value"
                  :key="index"
                ) {{ c_item.label }}
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="item.placeholder" clearable :disabled="item.isDisabled")
            template(v-if="item.type === 'radio'")
              RadioGroup.beautiful-radio-group(type="button" v-model="formData[item.model]")
                Radio.display-inline-block(v-for="(c_item, index) of item.radioArr" :label="c_item.value" :key="index") {{c_item.label}}
            template(v-if="item.type === 'interval'")
              DatePicker.pull-left.interval-date-140(:value="formData[item.model1]" :placeholder="item.placeholder1" type="date" @on-change="handleChangeDatePicker(item.model1, $event)")
              span.pl-10.pr-10.pull-left.line-h-32 --
              DatePicker.pull-left.interval-date-140.mr-20(:value="formData[item.model2]" :placeholder="item.placeholder2" type="date" @on-change="handleChangeDatePicker(item.model2, $event)")
              //- Button.pull-right(type="info" @click="searchFn") 查询
            template(v-if="item.type === 'button'")
              Button.search-btn(type="info" @click="searchFn") 查询

        Tabs(type="card" :value="formData.auditStatus" :animated="false" @on-click="chooseTab")
          .pl-20.pr-20.bg-white
            TabPane(label="未审核" name="0")
              Table.hasTitle-table.beautiful-table(:columns="thead" :data="tableData" :stripe="true" ref="demoTable"
                  @on-selection-change="handleOnSelectChange"
                )
                  .clearfix.overflow-hidden(slot="header")
                    .table-title-lefttxt.pull-left
                      |合计
                      span.text-info.pl-5.pr-5.font-weight {{tableComone.totalRows}}
                      |条
                    .pull-right.table-title-btns
                      //- Button(type="info" ghost @click="exportTreatmentEnjoyReviewListSocialSecurity") 导出
                  template(slot-scope="{ row, index }" slot="action")
                    //- Poptip.mr-10(trigger="hover" title="合同附件" :disabled="row.u_fileList.length == 0" )
                    //-   div(slot="content" style='z-index:999;')
                    //-     .u-d-info(v-for="(item, index) in row.u_fileList" :key="index" @click="handleDownLoad(item)") {{item.name}}
                    Button.mr-10(size="small" @click="handleShowCompleteModal(row.id,row.insuredTypeName,row)" v-if='hasSave') 完成
                    Button.mr-10(size="small" v-if='row.linkSort!=1 && hasBack' @click='isDelModal(row.treatmentEnjoyId,"back")') 退回上一级
                    Button.mr-10(size="small" v-if='hasEnd' @click='isDelModal(row.treatmentEnjoyId,"end")') 终止待遇
                    Button(size="small" :disabled="row.u_fileList.length == 0"  @click="handleDownLoad(row.u_fileList)" v-if='row.linkSort != 1') 查看上一环节附件
                  .clearfix.pl-20.pr-20(slot="footer")
                    Page(
                      :total="tableComone.totalRows"
                      @on-change="onChangePage"
                      @on-page-size-change="onpageSizeChange"
                      show-sizer
                      show-total
                      placement="top"
                      prev-text="上一页"
                      next-text="下一页"
                      :page-size-opts="[10, 20, 30, 50, 100]"
                    )
            TabPane(label="已审核" name="1")
              Table.hasTitle-table.beautiful-table(:columns="thead1" :data="tableData" :stripe="true" ref="demoTable"
                @on-selection-change="handleOnSelectChange"
              )
                .clearfix.overflow-hidden(slot="header")
                  .table-title-lefttxt.pull-left
                    |合计
                    span.text-info.pl-5.pr-5.font-weight {{tableComone.totalRows}}
                    |条
                  .pull-right.table-title-btns
                template(slot-scope="{ row, index }" slot="action")
                  //- Poptip.mr-10(trigger="hover" title="合同附件" :disabled="row.u_fileList.length == 0" )
                  //-   div(slot="content" style='z-index:999;')
                  //-     .u-d-info(v-for="(item, index) in row.u_fileList" :key="index" @click="handleDownLoad(item)") {{item.name}}
                  //-   Button(:disabled="row.u_fileList.length == 0") 查看上一环节附件
                  Button.mr-10(:disabled="row.u_fileList.length == 0"  @click="handleDownLoad(row.u_fileList)" v-if='row.linkSort != 1') 查看上一环节附件
                  Button(type='info' :disabled="row.fileList.length == 0"  @click="handleDownLoad(row.fileList)") 查看
                  //- Poptip(trigger="hover" title="合同附件" :disabled="row.fileList.length == 0" )
                  //-   div(slot="content" style='z-index:999;')
                  //-     .u-d-info(v-for="(item, index) in row.fileList" :key="index" @click="handleDownLoad(item)") {{item.name}}
                  //-   Button(:disabled="row.fileList.length == 0") 查看
                .clearfix.pl-20.pr-20(slot="footer")
                  Page(
                    :total="tableComone.totalRows"
                    @on-change="onChangePage"
                    @on-page-size-change="onpageSizeChange"
                    show-sizer
                    show-total
                    placement="top"
                    prev-text="上一页"
                    next-text="下一页"
                    :page-size-opts="[10, 20, 30, 50, 100]"
                  )

    //- 办理完成弹窗
    CompleteSocialWagesModal(ref="CompleteSocialWagesModal" @query="searchFn")
    CheckDownloadModal(ref="CheckDownloadModal")
</template>

<script>
import config from '@/config'
import { Common } from '@/utils/common.js'
import { ReceivableBillApi } from '@/api/ReceivableBill.api.js'
import { EnumApi } from '@/api/Enum.api.js'
import { SocialWagesThead2, SocialWagesThead3 } from './tableHead.js'
import _cloneDeep from 'clone-deep'
import { TreatmentApi } from '@/api/Treatment.api.js'
import { TreatmentEnjoyManageApi } from '@/api/TreatmentEnjoyManage.api.js'
import { TreatmentBasicsTypeApi } from '@/api/TreatmentBasicsType.api.js'
import { TreatmentEnjoyAuditApi } from '@/api/TreatmentEnjoyAudit.api.js'
import CompleteSocialWagesModal from './modal/CompleteSocialWagesModal.vue'
import CheckDownloadModal from './modal/CheckDownloadModal.vue'
import { constants } from 'fs';
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro

export default {
  name: 'socialWagesAudit', // 社保待遇审核

  components: {
    CompleteSocialWagesModal,
    CheckDownloadModal
  },
  computed: {
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 查询
    hasFind () {
      // return true
      return this.actionArr.indexOf('Find') > -1
    },
    // 保存
    hasSave () {
      // return true
      return this.actionArr.indexOf('Save') > -1
    },
    // 退回
    hasBack () {
      // return true
      return this.actionArr.indexOf('Back') > -1
    },
    // 终止
    hasEnd () {
      // return true
      return this.actionArr.indexOf('End') > -1
    }

  },
  data () {
    return {
      thead: _cloneDeep(SocialWagesThead2),
      thead1: _cloneDeep(SocialWagesThead3),
      tableData: [],
      detailCurrent: '1',
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10, // 当前页面展示条数
        agentCount: 0, // 办理中
        doneCount: 0 // 办理中
      },
      formData: {
        auditStatus: 0,
        securityType: 1,
        employeeName: '',
        companyId: '',
        idCardNos: '',
        customerServiceId: '',
        treatmentTypeId: '',
        insuredTypeId: '',
        enjoyType:1
      },
      formItem: [
        { type: 'input', label: '客户名称：', placeholder: '请选择客户名称', prop: 'customerName', model: 'customerName', isDisabled: false, style: 'ivu-col-span-6' },
        { type: 'select', label: '所属客服：', placeholder: '请选择所属客服', prop: 'customerServiceId', model: 'customerServiceId', isDisabled: false, style: 'ivu-col-span-6', options: 'server' },
        { type: 'input', label: '姓名：', placeholder: '请输入姓名', prop: 'employeeName', model: 'employeeName', isDisabled: false, style: 'ivu-col-span-6' },
        { type: 'input', label: '身份证号码：', placeholder: '请输入身份证号码', prop: 'idCardNos', model: 'idCardNos', isDisabled: false, style: 'ivu-col-span-6' },
        { type: 'select', label: '参保险种：', placeholder: '请选择参保险种', prop: 'insuredTypeId', model: 'insuredTypeId', isDisabled: false, style: 'ivu-col-span-6', options: 'insuredTypeId', fn: 'getInsuredTypeId' },
        { type: 'select', label: '待遇名称：', placeholder: '请选择待遇名称', prop: 'treatmentTypeId', model: 'treatmentTypeId', isDisabled: true, style: 'ivu-col-span-6', options: 'treatmentTypeId' },
        { type: 'button', isDisabled: false, style: 'ivu-col-span-6'  }
      ],
      rules: {
      },
      selectedEmployeeId: [], // 勾选的id集合,array格式
      selectedEmployeeArr: [], // 勾选的id, name数组集合
      arrListDown: {
        tempOps: [],
        defaultRadioArr: [{ value: '1', label: '是' }, { value: '0', label: '否' }],
        insuredTypeId: [],
        parameterstatus: [],
        server: [],
        companyList: [],
        employeeList: [],
        treatmentParametersEnableList: []
      },
    }
  },

  mounted () {
    // this.getEnum()
    this.servers()
    this.getInsuranceTypeList()
    this.getCustomerNameList()
    this.query()
  },

  methods: {
    isDelModal (id,type) {
      this.$Modal.confirm({
        title: '是否确认'+(type=='back'?'退回上一级':type=='end'?'终止待遇':''),
        onOk: () => {
          if (type == 'back'){
            this.back(id)
          }else{
            this.end(id)
          }
        }
      })
    },
    async back (id) {
      console.log(id)
      let res = await TreatmentEnjoyAuditApi.back({id:id})
      console.log('退回上一级: ', res)
      if (res.status === 200 && res.data.success) {
        var result = res.data.data
        this.query()
      }
    },
    async end (id) {
      let res = await TreatmentEnjoyAuditApi.end({id:id})
      console.log('终止待遇: ', res)
      if (res.status === 200 && res.data.success) {
        this.query()
      }
    },


    // 切换tab
    chooseTab (index) {
      if (index === this.formData.auditStatus) {
        return false
      } else {
        this.formData.auditStatus = index
        this.query()
      }
    },

    // 监听所有调用的方法
    listenCall (methodsWords, ...values) {
      this[methodsWords](...values)
    },
    
    // 获取客服
    async servers () {
      var params = {
        PageIndex: 1,
        PageSize: 100,
        Args: ''
      }
      Common.servers(params, this.arrListDown, 'server')
    },

    // 获取参保险种页面数据源
    async getInsuranceTypeList () {
      let res = await TreatmentBasicsTypeApi.getInsuranceTypeList()
      console.log('获取参保险种页面数据源: ', res)
      if (res.status === 200 && res.data.success) {
        var result = res.data.data.slice(0,5)
        for (var i in result) {
          result[i].label = result[i].text
        }
        this.arrListDown.insuredTypeId = result
      }
    },

    // 获取客户下拉内容
    async getCustomerNameList () {
      var params = {
        PageIndex: 1,
        PageSize: 10000
      }
      let res = await TreatmentEnjoyManageApi.customerNameList(params)
      console.log('res: ', res)
      if (res.status === 200 && res.data.success) {
        this.arrListDown.companyList = res.data.data.map(item => {
          return { label: item.value, value: item.key }
        })
      }
    },

    // 获取社保待遇名称列表
    async getInsuredTypeId (modal, val) {
      if (val) {
        this.arrListDown.treatmentTypeId = []
        this.formData.treatmentTypeId = ''
        var params = {
          insuredTypeId: val,
          HasPaging: true,
          PageIndex: 1,
          PageSize: 300
        }
        let res = await TreatmentBasicsTypeApi.getBasicsTypeList(params)
        console.log('客户薪资res: ', res)
        if (res.status === 200 && res.data.success && res.data.data) {
          this.formItem[5].isDisabled = false
          this.arrListDown.treatmentTypeId = res.data.data.map(item => {
            return { label: item.text, value: item.value }
          })
        } else {
          this.formItem[5].isDisabled = true
        }
      }
    },

    // 获取参保险种页面数据源
    async getInsuranceTypeList () {
      let res = await TreatmentBasicsTypeApi.getInsuranceTypeList()
      console.log('获取参保险种页面数据源: ', res)
      if (res.status === 200 && res.data.success) {
        var result = res.data.data.slice(0,5)
        for (var i in result) {
          result[i].label = result[i].text
        }
        this.arrListDown.insuredTypeId = result
      }
    },

    // 搜索
    searchFn () {
      this.tableComone.pageIndex = 1
      this.query()
    },

    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage (val) {
      this.tableComone.pageIndex = val
      this.query()
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange (val) {
      this.tableComone.pageIndex = 1
      this.tableComone.pageSize = val
      this.query()
    },
    /**
     * 分页查询接口
     * @param {Object} obj {pageIndex, pageSize}
     */
    async query () {
      var params = {
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize
      }
      let res = await TreatmentEnjoyAuditApi.getList({ ...params, ...this.formData })
      console.log('分页查询接口res: ', res)
      if (res.status === 200 && res.data.success) {
        this.tableData = res.data.data
        this.tableComone.totalRows = res.data.totalRows
        this.tableComone.agentCount = res.data.agentCount
        this.tableComone.doneCount = res.data.doneCount
        let result = res.data.data
        for (var j in result) {
          let annexNameArr = result[j].annexName?result[j].annexName.split(','):result[j].annexName
          let pathArr = result[j].path?result[j].path.split(','):result[j].path
          let idArr = result[j].annexId ? result[j].annexId.split(',') : []
          let fileList = []
          for (let i in pathArr) {
            fileList[i]={
              path: pathArr[i],
              name: annexNameArr[i],
              id: idArr[i]
            }
          }
          result[j].fileList = fileList
          let u_annexNameArr = result[j].upperAnnexName?result[j].upperAnnexName.split(','):result[j].upperAnnexName
          let u_idArr = result[j].upperAnnexId ? result[j].upperAnnexId.split(',') : []
          let u_fileList = []
          for (let i in u_annexNameArr) {
            u_fileList[i]={
              name: u_annexNameArr[i],
              id: u_idArr[i]
            }
          }
          result[j].u_fileList = u_fileList
        }
        this.tableData = result
        console.log(result,'result-------------')
      } else {
        this.tableData = []
      }
      this.loading = false
    },
    // async query () {
    //   var params = {
    //     HasPaging: true,
    //     PageIndex: this.tableComone.pageIndex,
    //     PageSize: this.tableComone.pageSize
    //   }
    //   let res = await TreatmentEnjoyAuditApi.getList({ ...params, ...this.formData })
    //   console.log('分页查询接口res: ', res)
    //   if (res.status === 200 && res.data.success) {
    //     this.tableData = res.data.data
    //     this.tableComone.totalRows = res.data.totalRows
    //     this.tableComone.agentCount = res.data.agentCount
    //     this.tableComone.doneCount = res.data.doneCount
    //   } else {
    //     this.tableData = []
    //   }
    //   this.loading = false
    // },

    // 表格选择操作
    handleOnSelectChange (value) {
      console.log(value,'表格选择操作')
      this.selectedEmployeeArr = value.map((item) => {
        return { id: item.id, name: item.name }
      })
      this.selectedEmployeeId = value.map((item) => {
        return item.id
      })
      console.log('列表勾选数组1', this.selectedEmployeeArr)
      console.log('列表勾选数组2', this.selectedEmployeeId)
    },

    // 日期选择
    handleChangeDatePicker (model, val) {
      console.log('model: ', model)
      console.log('val: ', val)
      this.formData[model] = val
    },

    // 导出待遇管理
    async exportTreatmentEnjoyReviewListSocialSecurity () {      
      var params = {
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize,
        IdList: this.selectedEmployeeId.join(',')
      }
      let res = await TreatmentEnjoyManageApi.export({ ...params, ...this.formData })
      console.log('导出待遇管理res: ', res)
      if (res.status === 200 && res.data.success) {
        let objectUrl = '/' + res.data.data.replace(/\\/g, '\/')
        const link = document.createElement('a')
        link.download = ''
        link.href = objectUrl
        link.click()
      }
    },

    // 显示完成弹窗
    handleShowCompleteModal (id,insuredTypeName,row) {
      console.log(row)
      this.$refs.CompleteSocialWagesModal.show(id)
      this.$refs.CompleteSocialWagesModal.formData.completeTime = new Date()
      if (insuredTypeName != '工伤') {
        this.$refs.CompleteSocialWagesModal.formItem = this.$refs.CompleteSocialWagesModal.formItem.filter(function(element, index) {
          return element['model'] != 'appraisalGrade'; 
        })
      }
      if (row.auditTime != null) {
        this.$refs.CompleteSocialWagesModal.getModel(row.id)
      }
    },
    
    // 附件下载
    handleDownLoad (row) {
      this.$refs.CheckDownloadModal.show()
      this.$refs.CheckDownloadModal.fileList = row
      this.$refs.CheckDownloadModal.baseUrl = baseUrl
    }
  } // methods end
}
</script>

<style lang="less">
  .ivu-tabs-bar{
    margin: 0;
  }
  // .ivu-table-fixed-body{
  //   overflow: visible;
  // }
</style>
